<template>
  <div class="about">
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
      <el-form-item label="FM类型">
        <el-input v-model="queryInfo.name" placeholder="请输入关键字" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="searchName">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="mb20">
      <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
      <el-button type="danger" icon="Delete" plain>删除</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="fmId" label="编号" width="75" />
      <el-table-column prop="fmName" label="标题" width="80" />
      <el-table-column prop="fmMusic" label="音频" width="350">
        <template #default="scope">
          <audio width="100%" height="100%" controls>
            <source :src="url + scope.row.fmMusic">
          </audio>
        </template>
      </el-table-column>
      <el-table-column prop="fmImg" label="图片" width="120">
        <template #default="scope">
          <el-image v-if="scope.row.fmImg" style="width: 100px; height: 100px" :src="url + scope.row.fmImg"
            :fit='"cover"' />
        </template>
      </el-table-column>
      <el-table-column prop="coursetypeId" label="课程编号" width="120" />
      <el-table-column prop="coursetype.courseTypeName" label="课程名" width="120" />

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="toEdit(scope.row)">修改</el-button>
          <el-button link type="primary" @click="onDel(scope.row.fmId)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
    :page-sizes="[2, 5, 8, 10]" size="default" background="false" layout="total, sizes, prev, pager, next, jumper"
    :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  <!-- 添加，编辑弹框 -->

  <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
    <el-form :model="fm">
      <el-form-item label=" 编号" :label-width="formLabelWidth">
        <el-input v-model="fm.fmId" autocomplete="off" />
      </el-form-item>
      <el-form-item label=" 名称" :label-width="formLabelWidth">
        <el-input v-model="fm.fmName" autocomplete="off" />
      </el-form-item>
   
      <el-form-item label="音频">
        <el-upload
          v-model:file-list="fileList1"
          class="avatar-uploader"
          action="http://localhost:80/file/upload"
          :show-file-list="false"
          :on-success="handleAudioSuccess"
        >
          <template #trigger>
            <el-button type="primary">上传音频</el-button>
          </template>
          <!-- <audio v-if="fmMusic" :src="fmMusic" controls class="avatar-audio"></audio> -->
          <!-- <el-icon class="avatar-uploader-icon">
            <Plus />
          </el-icon> -->
        </el-upload>
      </el-form-item>
      <el-form-item label=" 图片" :label-width="formLabelWidth">
        <el-upload v-model:file-list="fileList" class="avatar-uploader" action=" http://localhost:80/file/upload"
          :show-file-list="false" :on-success="handleAvatarSuccess">
          <img v-if="fmImg" :src="fmImg" class="avatar" />
          <el-icon class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label=" 课程编号" :label-width="formLabelWidth">
        <el-input v-model="fm.coursetypeId" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const fmImg = ref('');
const fmMusic = ref('');

const fileList = ref([]);
const fileList1 = ref([]);

const saveOrUpdateVisible = ref(false);
const fm = ref({
  fmId: 0,
  fmName: '',
  fmMusic: '',
  fmImg: '',
  coursetypeId: 0,
  coursetype: {
    courseTypeName: '',
  }
})

const handleAvatarSuccess = (response, uploadFile) => {
  fmImg.value = URL.createObjectURL(uploadFile.raw);
  fm.value.fmImg = response.data;
}

const handleAudioSuccess = (response, uploadFile) => {
  fmMusic.value = URL.createObjectURL(uploadFile.raw);
  fm.value.fmMusic = response.data;
  ElMessage({
    message: '音频上传成功！',
    type: 'success',
  });
};

const saveOrUpdateTitle = ref('添加')
const toEdit = (row) => {
  saveOrUpdateVisible.value = true;
  saveOrUpdateTitle.value = '编辑';
  fm.value = row;
  fileList.value = [
    {
      name: row.imageUrl,
      url: url.value + row.imageUrl,
    }
  ];
  fileList1.value = [
    {
      name: row.audioUrl,
      url: url.value + row.audioUrl,
    }
  ];
}

const toAdd = () => {
  saveOrUpdateVisible.value = true;
  saveOrUpdateTitle.value = '添加';
  fm.value = {
    fmId: 0,
    fmName: '',
    fmMusic: '',
    fmImg: '',
    courseTypeId: 0,
    coursetype: {}
  }
}

const close = () => {
  saveOrUpdateVisible.value = false;
  fm.value = {
    fmid: 0,
    fmName: '',
    fmMusic: '',
    fmImg: '',
    coursetypeId: 0,
    coursetype: {}
  }
}

const saveOrUpdate = async () => {
  try {
    if (saveOrUpdateTitle.value == '添加') {
      const resp = await axios.post('/fm/fmAdd', fm.value);
      if (resp.data.code == 1) {
        ElMessage.success('添加成功！');
        getList();
        close();
      } else {
        ElMessage.warning('添加失败！');
      }
    } else if (saveOrUpdateTitle.value == '编辑') {
      const resp = await axios.put('/fm/fmUpdate', fm.value);
      if (resp.data.code == 1) {
        ElMessage.success('修改成功！');
        getList();
        close();
      } else {
        ElMessage.warning('修改失败！');
      }
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试！');
  }
};

const total = ref(0)
onMounted(() => {
  getList();
})

const queryInfo = ref({
  pageNum: 1,
  pageSize: 2,
  name: '',
})

const searchName = () => {
  getList();
}

const getList = () => {
  axios.get('/fm/fmSelectByName', { params: queryInfo.value })
    .then(resp => {
      let result = resp.data;
      if (result.code == 1) {
        tableData.value = result.data.list;
        total.value = result.data.total;
      } else {
        console.log('获取fm列表失败')
      }
    })
}

const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getList();
}

const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getList();
}

const url = ref('http://localhost:80/file/downLoad?fileName=')

const onDel = id => {
  ElMessageBox.confirm('真的要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios.delete('fm/fmDelete/' + id)
        .then(resp => {
          let result = resp.data;
          if (result.code == 1) {
            getList();
            ElMessage({
              message: '删除成功！',
              type: 'success',
            })
          } else {
            ElMessage({
              message: '删除失败！',
              type: 'warning',
            })
          }
        })
    })
    .catch(() => { })
}

const tableData = ref([])
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px solid black;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-audio {
  width: 100%;
  height: 100px;
  display: block;
  margin-top: 10px;
}
</style>